package com.tmptSource.controller.action;

import com.opensymphony.xwork2.ActionSupport;
import com.tmpt.dto.Result;
import com.tmpt.utils.report.ExcelUtils;
import com.tmptSource.dto.A2userDto;
import com.tmptSource.dto.OwTaskDto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.service.intf.IA2userService;
import com.tmpt.utils.*;
import com.tmptSource.service.intf.IOwTaskService;
import lombok.Getter;
import lombok.Setter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Getter
@Setter
@Controller(value = "a2userAction")
@Scope("prototype")
public class A2userAction extends ActionSupport {
    private Logger log = Logger.getLogger(this.getClass());


    //------------
    //与页面交互的分页和排序
    //--------------
    private int page = 0;
    private int rows = 0;
    private String sortColumn;
    private String sortOrder;

    //------------
    //与页面交互的业务数据
    //--------------
    private String id;
    private String a2postName;
    private String rolenames;
    private String companyId;
    private String owUserType;
    private String loginname;
    private String password;
    private String appLoginname;
    private String appPassword;
    private String a2postId;
    private String name;
    private String jobNumber;
    private String email;
    private String idcardno;
    private String sex;
    private String telephone;
    private String phone;
    private String logintimelast;
    private String logintimelast_Start;
    private String logintimelast_End;
    private String logintimes;
    private String createdate;
    private String createdate_Start;
    private String createdate_End;
    private String createman;
    private String a2deptId;
    private String modifydate;
    private String modifydate_Start;
    private String modifydate_End;
    private String deleteflag;
    private String modifyman;
    private String createmanId;
    private String modifymanId;
    private String owrRegionId;

    public String getOwrRegionId() {
        return owrRegionId;
    }

    public void setOwrRegionId(String owrRegionId) {
        this.owrRegionId = owrRegionId;
    }

    //返回结果
    private String result;
    //返回结果
    private List<Map<String, Object>> jsonArrayResult = new ArrayList<Map<String, Object>>();


    @Resource
    private IA2userService a2userService;
    @Resource
    private IOwTaskService owTaskService;


    /**
     * 分页查询列表
     *
     * @return
     */
    public String queryListBySearch() {
        try {

            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //查询参数
            //分页/排序查询条件
            PageDto pageDto = new PageDto();
            //默认主键desc
            if (StringUtils.isNull(sortColumn)) {
                sortColumn = "id";
                sortOrder = "desc";
            }
            pageDto.setPageCurrent(page - 1);
            pageDto.setPageSize(rows);
            pageDto.setSortColumn(sortColumn);
            pageDto.setSortOrder(sortOrder);

            //查询条件
            A2userDto a2userParam = new A2userDto();
            a2userParam.setOwUserType(this.owUserType);
            a2userParam.setA2postId(this.a2postId);
            a2userParam.setName(this.name != null ? "%" + this.name + "%" : null);
            a2userParam.setCreatedate_Start(this.createdate_Start);
            a2userParam.setCreatedate_End(this.createdate_End);
            a2userParam.setCreatedate(this.createdate);
            a2userParam.setOwrRegionId(this.getOwrRegionId());

            //data limit control
            String requireUrl = request.getRequestURI().toString();
            String queryString = request.getQueryString();
            String contextPath = request.getContextPath();
            //data limit parameters
            String userId = WebUtils.getUserId();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("userId", userId);
            paramMap.put("contextPath", contextPath);
            paramMap.put("requireUrl", requireUrl);
            paramMap.put("queryString", queryString);

            //调用远程服务
            Result<A2userDto> resultObj = a2userService.pagination(a2userParam, pageDto, paramMap);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            Map<String, Object> resultMap = resultObj.getResultMap();

            //分页记录
            List<A2userDto> list = (List<A2userDto>) resultMap.get("rows");
            JSONArray jsonArrayRows = JSONArray.fromObject(list);

            //分页总记录数
            int total = 0;
            if (resultMap.get("total") != null) {
                total = Integer.parseInt(resultMap.get("total").toString());
            }

            //分页合计（select '合计' as c1, sum(balance) as c2 ....）
            JSONArray jsonArrayFooter = null;
            if (resultMap.get("footer") != null) {
                jsonArrayFooter = JSONArray.fromObject(resultMap.get("footer"));
            }

            JSONObject json = new JSONObject();
            json.put("total", total);
            json.put("rows", jsonArrayRows);
            //json.put("reportSqlString",reportSqlString);
            if (jsonArrayFooter != null) {
                json.put("footer", jsonArrayFooter);
            }

            this.result = json.toString();
            JsonPaginationUtils.responseWriter(response, this.result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "jsonResult";
    }

    /**
     * 分页查询列表(没有数据边界)
     *
     * @return
     */
    public String queryListBySearchNoDataLimit() {
        try {

            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //查询参数
            //分页/排序查询条件
            PageDto pageDto = new PageDto();
            //默认主键desc
            if (StringUtils.isNull(sortColumn)) {
                sortColumn = "id";
                sortOrder = "desc";
            }
            pageDto.setPageCurrent(page - 1);
            pageDto.setPageSize(rows);
            pageDto.setSortColumn(sortColumn);
            pageDto.setSortOrder(sortOrder);

            //查询条件
            A2userDto a2userParam = new A2userDto();
            a2userParam.setOwUserType(this.owUserType);
            a2userParam.setA2postId(this.a2postId);
            a2userParam.setName(this.name != null ? "%" + this.name + "%" : null);
            a2userParam.setCreatedate_Start(this.createdate_Start);
            a2userParam.setCreatedate_End(this.createdate_End);
            a2userParam.setCreatedate(this.createdate);

            //调用远程服务
            Result<A2userDto> resultObj = a2userService.pagination(a2userParam, pageDto);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            Map<String, Object> resultMap = resultObj.getResultMap();

            //分页记录
            List<A2userDto> list = (List<A2userDto>) resultMap.get("rows");
            JSONArray jsonArrayRows = JSONArray.fromObject(list);

            //分页总记录数
            int total = 0;
            if (resultMap.get("total") != null) {
                total = Integer.parseInt(resultMap.get("total").toString());
            }

            //分页合计（select '合计' as c1, sum(balance) as c2 ....）
            JSONArray jsonArrayFooter = null;
            if (resultMap.get("footer") != null) {
                jsonArrayFooter = JSONArray.fromObject(resultMap.get("footer"));
            }

            JSONObject json = new JSONObject();
            json.put("total", total);
            json.put("rows", jsonArrayRows);
            //json.put("reportSqlString",reportSqlString);
            if (jsonArrayFooter != null) {
                json.put("footer", jsonArrayFooter);
            }

            this.result = json.toString();
            JsonPaginationUtils.responseWriter(response, this.result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "jsonResult";
    }


    /**
     * 分页查询列表(没有数据边界)
     *
     * @return
     */
    public String download() {
        try {
            page = 1;
            rows = 1000000;

            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //查询参数
            //分页/排序查询条件
            PageDto pageDto = new PageDto();
            //默认主键desc
            if (StringUtils.isNull(sortColumn)) {
                sortColumn = "id";
                sortOrder = "desc";
            }
            pageDto.setPageCurrent(page - 1);
            pageDto.setPageSize(rows);
            pageDto.setSortColumn(sortColumn);
            pageDto.setSortOrder(sortOrder);

            //查询条件
            A2userDto a2userParam = new A2userDto();
            a2userParam.setOwUserType(this.owUserType);
            a2userParam.setA2postId(this.a2postId);
            a2userParam.setName(this.name != null ? "%" + this.name + "%" : null);
            a2userParam.setCreatedate_Start(this.createdate_Start);
            a2userParam.setCreatedate_End(this.createdate_End);
            a2userParam.setCreatedate(this.createdate);

            //调用远程服务
            Result<A2userDto> resultObj = a2userService.pagination(a2userParam, pageDto);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            Map<String, Object> resultMap = resultObj.getResultMap();

            //分页记录
            List<A2userDto> list = (List<A2userDto>) resultMap.get("rows");
            JSONArray jsonArrayRows = JSONArray.fromObject(list);

            //分页总记录数
            int total = 0;
            if (resultMap.get("total") != null) {
                total = Integer.parseInt(resultMap.get("total").toString());
            }

            //分页合计（select '合计' as c1, sum(balance) as c2 ....）
            JSONArray jsonArrayFooter = null;
            List<A2userDto> listFooter = null;
            if (resultMap.get("footer") != null) {
                listFooter = (List<A2userDto>) resultMap.get("footer");
                jsonArrayFooter = JSONArray.fromObject(listFooter);
            }

            JSONObject json = new JSONObject();
            json.put("total", total);
            json.put("rows", jsonArrayRows);
            //json.put("reportSqlString",reportSqlString);
            if (jsonArrayFooter != null) {
                json.put("footer", jsonArrayFooter);
            }

            //this.result = json.toString();
            //JsonPaginationUtils.responseWriter(response, this.result);

            //报表
            List<List<String>> rowList = new ArrayList<List<String>>();
            List<String> col = null;

            col = new ArrayList<String>();
            //col.add("ID");
            col.add("姓名");
            col.add("员工类型");
            col.add("性别");
            col.add("后台登录名");
            col.add("APP登录名");
            col.add("工号");
            col.add("联系方式");
            rowList.add(col);

            for (A2userDto a2userDto : list) {
                col = new ArrayList<String>();
                //col.add(a2userDto.getId());
                col.add(a2userDto.getName());
                col.add(a2userDto.getOwUserType_Str());
                col.add(a2userDto.getSex_Str());
                col.add(a2userDto.getLoginname());
                col.add(a2userDto.getAppLoginname());
                col.add(a2userDto.getJobNumber());
                col.add(a2userDto.getPhone());
                rowList.add(col);
            }

            ExcelUtils.downloadReport("用户列表", rowList, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "jsonResult";
    }


    /**
     * 伪删除数据
     *
     * @return
     */
    public String removeData() {
        Result resultObj = new Result();
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //参数
            String adminMan = WebUtils.getUsername();//加入管理员

            //调用远程服务
            resultObj = a2userService.deleteById(Long.valueOf(id), adminMan);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            this.jsonArrayResult.add(resultObj.getResultMap());

        } catch (Exception e) {
            e.printStackTrace();
            resultObj.fault("error:系统出错:" + e.getLocalizedMessage());
            this.jsonArrayResult.add(resultObj.getResultMap());
        }

        return "jsonArray";
    }


    /**
     * 编辑数据
     *
     * @return
     */
    public String editData() {
        Result<A2userDto> resultObj = new Result();
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //参数
            A2userDto a2userDto = new A2userDto();
            String adminMan = WebUtils.getUsername();//加入管理员
            String userId = WebUtils.getUserId();
            a2userDto.setModifymanId(userId);
            a2userDto.setModifyman(adminMan);
            a2userDto.setCompanyId(WebUtils.getCompanyId());
            a2userDto.setId(this.id);
            //编辑数据
            a2userDto.setOwUserType(this.owUserType);
            a2userDto.setLoginname(this.loginname);
            //a2userDto.setPassword(this.password);
            a2userDto.setAppLoginname(this.loginname);
            //a2userDto.setAppPassword(this.appPassword);
            a2userDto.setA2postId(this.a2postId);
            a2userDto.setName(this.name);
            a2userDto.setJobNumber(this.jobNumber);
            a2userDto.setEmail(this.email);
            a2userDto.setIdcardno(this.idcardno);
            a2userDto.setSex(this.sex);
            a2userDto.setTelephone(this.telephone);
            a2userDto.setPhone(this.phone);
            a2userDto.setOwrRegionId(this.owrRegionId);

            //调用远程服务
            resultObj = a2userService.editData(a2userDto);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            this.jsonArrayResult.add(resultObj.getResultMap());

        } catch (Exception e) {
            e.printStackTrace();
            resultObj.fault("error:系统出错:" + e.getLocalizedMessage());
            this.jsonArrayResult.add(resultObj.getResultMap());
        }

        return "jsonArray";
    }

    /**
     * 添加数据
     *
     * @return
     */
    public String addData() {
        Result<A2userDto> resultObj = new Result();
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //插入参数
            A2userDto a2userDto = new A2userDto();
            String adminMan = WebUtils.getUsername();//加入管理员
            String userId = WebUtils.getUserId();
            a2userDto.setCreatemanId(userId);
            a2userDto.setCreateman(adminMan);
            a2userDto.setCompanyId(WebUtils.getCompanyId());
            //插入数据
            a2userDto.setOwUserType(this.owUserType);
            a2userDto.setLoginname(this.loginname);
            //a2userDto.setPassword(this.password);
            a2userDto.setAppLoginname(this.loginname);
            //a2userDto.setAppPassword(this.appPassword);
            a2userDto.setA2postId(this.a2postId);
            a2userDto.setName(this.name);
            a2userDto.setJobNumber(this.jobNumber);
            a2userDto.setEmail(this.email);
            a2userDto.setIdcardno(this.idcardno);
            a2userDto.setSex(this.sex);
            a2userDto.setTelephone(this.telephone);
            a2userDto.setPhone(this.phone);
            a2userDto.setOwrRegionId(this.owrRegionId);


            //调用远程服务
            resultObj = a2userService.addData(a2userDto);
            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            this.jsonArrayResult.add(resultObj.getResultMap());

        } catch (Exception e) {
            e.printStackTrace();
            resultObj.fault("error:系统出错:" + e.getLocalizedMessage());
            this.jsonArrayResult.add(resultObj.getResultMap());
        }
        return "jsonArray";
    }

    /**
     * 判断region_id是否有变化
     * 如果没有变化，继续编辑
     * 如果有变化，先查询当前用户是否有待办任务，如果有待办任务，返回“该员工存在未完成的双随机任务，若切换区域将自动移除TA未完成任务，确认切换？”
     *
     * @return
     */
    public String doublePairTaskExist_access() {
        Result<OwTaskDto> resultObj = new Result();
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = WebUtils.getRequest();
            HttpSession session = request.getSession();

            //插入参数 获取此用户id
            String userId = this.id;

            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("userId", userId);
			paramMap.put("owTaskType", "3");

            //调用远程服务
            resultObj = owTaskService.queryMyTaskWF(paramMap);

            if (!resultObj.isSuccess()) {
                this.result = "error:" + resultObj.getContent();
                JsonPaginationUtils.responseWriter(response, this.result);
                return "jsonResult";
            }
            this.jsonArrayResult.add(resultObj.getResultMap());

        } catch (Exception e) {
            e.printStackTrace();
            resultObj.fault("error:系统出错:" + e.getLocalizedMessage());
            this.jsonArrayResult.add(resultObj.getResultMap());
        }
        return "jsonArray";
    }


    //=====================================================
    // setter getter method
    //=====================================================
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getA2postName() {
        return a2postName;
    }

    public void setA2postName(String a2postName) {
        this.a2postName = a2postName;
    }

    public String getRolenames() {
        return rolenames;
    }

    public void setRolenames(String rolenames) {
        this.rolenames = rolenames;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public String getOwUserType() {
        return owUserType;
    }

    public void setOwUserType(String owUserType) {
        this.owUserType = owUserType;
    }

    public String getLoginname() {
        return loginname;
    }

    public void setLoginname(String loginname) {
        this.loginname = loginname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAppLoginname() {
        return appLoginname;
    }

    public void setAppLoginname(String appLoginname) {
        this.appLoginname = appLoginname;
    }

    public String getAppPassword() {
        return appPassword;
    }

    public void setAppPassword(String appPassword) {
        this.appPassword = appPassword;
    }

    public String getA2postId() {
        return a2postId;
    }

    public void setA2postId(String a2postId) {
        this.a2postId = a2postId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJobNumber() {
        return jobNumber;
    }

    public void setJobNumber(String jobNumber) {
        this.jobNumber = jobNumber;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getIdcardno() {
        return idcardno;
    }

    public void setIdcardno(String idcardno) {
        this.idcardno = idcardno;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getLogintimelast() {
        return logintimelast;
    }

    public void setLogintimelast(String logintimelast) {
        this.logintimelast = logintimelast;
    }

    public String getLogintimelast_Start() {
        return logintimelast_Start;
    }

    public void setLogintimelast_Start(String logintimelast_Start) {
        this.logintimelast_Start = logintimelast_Start;
    }

    public String getLogintimelast_End() {
        return logintimelast_End;
    }

    public void setLogintimelast_End(String logintimelast_End) {
        this.logintimelast_End = logintimelast_End;
    }

    public String getLogintimes() {
        return logintimes;
    }

    public void setLogintimes(String logintimes) {
        this.logintimes = logintimes;
    }

    public String getCreatedate() {
        return createdate;
    }

    public void setCreatedate(String createdate) {
        this.createdate = createdate;
    }

    public String getCreatedate_Start() {
        return createdate_Start;
    }

    public void setCreatedate_Start(String createdate_Start) {
        this.createdate_Start = createdate_Start;
    }

    public String getCreatedate_End() {
        return createdate_End;
    }

    public void setCreatedate_End(String createdate_End) {
        this.createdate_End = createdate_End;
    }

    public String getCreateman() {
        return createman;
    }

    public void setCreateman(String createman) {
        this.createman = createman;
    }

    public String getA2deptId() {
        return a2deptId;
    }

    public void setA2deptId(String a2deptId) {
        this.a2deptId = a2deptId;
    }

    public String getModifydate() {
        return modifydate;
    }

    public void setModifydate(String modifydate) {
        this.modifydate = modifydate;
    }

    public String getModifydate_Start() {
        return modifydate_Start;
    }

    public void setModifydate_Start(String modifydate_Start) {
        this.modifydate_Start = modifydate_Start;
    }

    public String getModifydate_End() {
        return modifydate_End;
    }

    public void setModifydate_End(String modifydate_End) {
        this.modifydate_End = modifydate_End;
    }

    public String getDeleteflag() {
        return deleteflag;
    }

    public void setDeleteflag(String deleteflag) {
        this.deleteflag = deleteflag;
    }

    public String getModifyman() {
        return modifyman;
    }

    public void setModifyman(String modifyman) {
        this.modifyman = modifyman;
    }

    public String getCreatemanId() {
        return createmanId;
    }

    public void setCreatemanId(String createmanId) {
        this.createmanId = createmanId;
    }

    public String getModifymanId() {
        return modifymanId;
    }

    public void setModifymanId(String modifymanId) {
        this.modifymanId = modifymanId;
    }

    public String getSortColumn() {
        return sortColumn;
    }

    public void setSortColumn(String sortColumn) {
        this.sortColumn = sortColumn;
    }

    public String getSortOrder() {
        return sortOrder;
    }

    public void setSortOrder(String sortOrder) {
        this.sortOrder = sortOrder;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public List<Map<String, Object>> getJsonArrayResult() {
        return jsonArrayResult;
    }

    public void setJsonArrayResult(List<Map<String, Object>> jsonArrayResult) {
        this.jsonArrayResult = jsonArrayResult;
    }

}
